package a.b;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.ResourceCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public abstract class SectionCursorAdatper extends ResourceCursorAdapter {
	private LayoutInflater mInflater;
	private String mSectionColumnName;
	private int mLayout;
	public SectionCursorAdatper(Context context, int sectionLayout, int contentLayout, Cursor c, String sectionColumnName) {
		super(context, contentLayout, new SectionCursor(c, sectionColumnName), true);
		mLayout = sectionLayout;
		mSectionColumnName = sectionColumnName;

		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public Cursor swapCursor(Cursor newCursor) {
		return super.swapCursor(new SectionCursor(newCursor, mSectionColumnName));
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		int positon = cursor.getPosition();
		if (isSection(positon)) {
			return mInflater.inflate(mLayout, null);
		} else {
			return super.newView(context, cursor, parent);
		}
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		int positon = cursor.getPosition();
		if (isSection(positon)) {
			bindSectionView(view, context, cursor);
		} else {
			bindContentView(view, context, cursor);
		}
	}

	private boolean isSection(int position) {
		return getItemId(position) == -1;
	}

	@Override
	public int getItemViewType(int position) {
		if (isSection(position)) {
			return 1;
		}
		return super.getItemViewType(position);
	}
	@Override
	public int getViewTypeCount() {
		return super.getViewTypeCount() + 1;
	}

	@Override
	public boolean areAllItemsEnabled() {
		return false;
	}

	@Override
	public boolean isEnabled(int position) {
		return !isSection(position);
	}

	protected abstract void bindSectionView(View view, Context context, Cursor cursor);
	protected abstract void bindContentView(View view, Context context, Cursor cursor);
}
